package manage.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import manage.model.IncomeType;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public class IncomeTypeServiceImpl implements IncomeTypeService {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @SuppressWarnings("unchecked")
    public List<IncomeType> findAll() {
       
        Query query = getEntityManager().createQuery("SELECT i FROM IncomeType i WHERE i.parent IS NULL ORDER BY sequence ASC, id DESC");
        List<IncomeType> items= query.getResultList();

        return items;
    }

     public List<IncomeType> findChildren(Integer parentId) {

        Query query = getEntityManager().createQuery("SELECT i FROM IncomeType i WHERE i.parent = " + parentId + " ORDER BY sequence ASC, id DESC");
        List<IncomeType> items= query.getResultList();

        return items;
    }

    private void save(IncomeType incomeType) {
        if (incomeType.getId() == null) {
            // new
            em.persist(incomeType);
        } else {
            // update
            em.merge(incomeType);
        }
    }

    public void remove(int id) {
        IncomeType incomeType = find(id);
        if (incomeType != null) {
            em.remove(incomeType);
        }
    }

    private EntityManager getEntityManager() {
        return em;
    }

    public IncomeType find(int id) {
        return em.find(IncomeType.class, id);
    }

    public void add(IncomeType incomeType) {
        this.save(incomeType);
    }

    public void update(IncomeType incomeType) {
        this.save(incomeType);        
    }

}
